Qodana против кода от ИИ: что нашёл статический анализ в Java-приложении
Источник: https://blog.jetbrains.com/qodana/2026/11/ai-generated-code-security-risks/
Краткое содержание
Статья блога Qodana объясняет, почему код, написанный ИИ-агентами, нужно проверять на безопасность, даже если функциональные тесты проходят: агент за один проход может изменить логику, зависимости, конфигурацию и тесты и пропустить ограничения, которых нет в описании задачи. Приводится исследование публичных Python- и JavaScript-фрагментов на GitHub, где нашли слабости в 43 категориях CWE, и рекомендация OWASP проверять любые целиком агентские изменения, включая зависимости и тесты. Статический анализ даёт ревьюеру отправные точки (потоки данных, небезопасные паттерны, уязвимые зависимости, зашитые значения), но каждое срабатывание требует контекста: достижим ли путь, что запускается в продакшене, какое исправление подходит.
Разбор Corporate Payments Portal
Авторы сканируют Corporate Payments Portal — Java 21 / Spring Boot приложение из бенчмарка RealVuln, где уязвимости намеренно заложены в ИИ-код (портал, платёжный API, мок банковского ядра, batch-воркер). Публичный отчёт Qodana содержит 65 находок в 21 файле, но это очередь на триаж, а не число эксплуатируемых дыр: многие дублируются или указывают на синтетические значения. Один случай, подчёркивают авторы, не показывает, как часто ИИ порождает уязвимости.
Уязвимая зависимость и XML
Модуль портала парсит XML-черновики через XStream версии 1.4.7 (portal/build.gradle), которую проверка зависимостей помечает как имеющую известные уязвимости:
implementation 'com.thoughtworks.xstream:xstream:1.4.7'
Отдельная taint-находка указывает на вызов, превращающий XML в Java-объекты:
new com.thoughtworks.xstream.XStream().fromXML(draft)
Данные берутся из cookie cpDeskDraft; контроллер проверяет лишь, что она не пуста, а клиент может её подменить. В XStream 1.4.7 нет списка разрешённых типов по умолчанию, так что десериализация может создать нежелательные объекты (влияние зависит от нагрузки и среды). Находка названа path traversal, и привязывать конкретный CVE к вызову по этим данным нельзя. Рекомендация: решить, нужна ли десериализация XML вообще; если да — обновить зависимость, задать allowlist типов и проверить отказ на неожиданный XML.
Зашитый запасной ключ
В конфигурации платёжного API ключ legacy-моста читается из Spring-свойства с запасным значением после двоеточия:
legacy-report-bridge:
intake-key: ${LEGACY_REPORT_BRIDGE_KEY:legacy-bridge-dev-key-9c1e}
То же значение дублируется в конструкторе LegacyReportBridge, а ключ уходит во внутренний сервис как параметр bridge-key. В бенчмарке значение синтетическое, но на практике, если переменная окружения не задана, приложение молча возьмёт учётные данные из репозитория. Инспекцию Hardcoded passwords пришлось расширить (поиск по подозрительным именам переменных), по умолчанию она этот паттерн не ловит. Рекомендация: убрать fallback в application.yml и в @Value, требовать ключ из внешнего хранилища секретов и падать на старте при его отсутствии, а dev-значения держать в dev-профиле.
Лицензионная находка
Аудит лицензий помечает транзитивную зависимость hibernate-core 6.5.3.Final: её лицензия LGPL-2.1-or-later в списке запрещённых для проекта с PROPRIETARY-LICENSE. Это сигнал политики, а не юридический вывод и не доказательство небезопасности; нужно сверить реальную политику и модель распространения, изучить условия и задокументировать исключение либо сменить зависимость.
Как использовать результаты
Авторы сводят выводы в таблицу «паттерн — что показывает Qodana — вопрос ревьюеру»: уязвимая зависимость (какие объекты XStream создаст из этой cookie), запасной ключ (может ли fallback сработать в проде), лицензия (разрешает ли политика). В статье упомянуто, что JetBrains Air позволяет комментировать диффы агента построчно, а Qodana даёт отдельный взгляд по сканированию кодовой базы; находки статьи получены только Qodana. Проверки можно запускать в CI. FAQ: у ИИ-кода нет универсальной «большей уязвимости», бенчмарк это не устанавливает; статический анализ не находит всё, включая правила авторизации и поведение рантайма; Qodana не может автоматически «защитить» код.
Значимость
Материал — продуктовая статья, но с практичной рамкой: статический анализ задаёт вопросы, а решение принимает человек, и «проходящие тесты» не равны «безопасно».
🧾 Транскрипт (формат)
AI-Generated Code Security Risks: What Qodana Found in a Java App Source: https://blog.jetbrains.com/qodana/2026/11/ai-generated-code-security-risks/
Adding search functionality, converting a document, or connecting a service sound like small changes. An AI coding agent may take it on in one pass, changing application logic, dependencies, configuration, and tests along the way. The result may pass functional tests and still contain security vulnerabilities.
Static analysis can surface some AI-generated code security risks, while reviewers and targeted tests determine which findings matter in practice. Where can external input travel? What happens if a configuration value is missing? Do the new dependencies introduce risks the functional tests never exercise? The same questions matter in any codebase, including code written with AI.
A study of AI-generated Python and JavaScript snippets in public GitHub projects found weaknesses across 43 Common Weakness Enumeration (CWE) categories. OWASP recommends reviewing any fully agent-produced changes, including dependencies and tests. Passing tests are useful evidence, but they don’t answer every security question.
Static analysis gives reviewers a place to start. It can point to data flows, unsafe code patterns, vulnerable dependencies, and hardcoded values, but each finding still needs context. A reviewer must check whether the path is reachable, what runs in production, and which fix fits the application.
Table of Contents Why AI-generated code still needs a security review Scanning the Corporate Payments Portal with Qodana What Qodana found in the application A vulnerable dependency and an XML-processing call A hardcoded fallback remains in configuration A license finding raises a different question
How to use the findings in a security review FAQ
Why AI-generated code still needs a security review An agent may implement the requested behavior while missing constraints that live outside the feature description. Passing functional tests may still leave questions about how data crosses trust boundaries or how deployment settings affect security. OWASP’s secure code review guidance calls for understanding business requirements, tracing data flows, and checking configuration and deployment. These checks often span modules.
Qodana points to relevant paths and patterns, then reviewers supply the application context needed to judge them.
Scanning the Corporate Payments Portal with Qodana We examined the Corporate Payments Portal, a Java app from the RealVuln Benchmark, alongside its public Qodana report. The benchmark deliberately seeds vulnerabilities in AI-generated code, giving us concrete findings to investigate. We’ll follow several of them from the code to the questions a reviewer would ask. This single case does not tell us how often AI introduces vulnerabilities.
The Corporate Payments Portal uses Java 21 and Spring Boot and includes a web portal, a payment API, a mock core banking service, and a batch worker. We use a pinned source revision so the excerpts match the report. That matters because a risky flow may begin with a controller and end with a service, while a dependency or configuration value can create a separate concern even when a Java method looks ordinary.
We ran a focused Qodana scan for data flows, vulnerable dependencies, hardcoded passwords, and dependency licenses. The password inspection was configured more broadly than its defaults for this example. Qodana’s findings provide starting points – a trace can show where data may travel, and a dependency alert can identify a version with known advisories. Neither, by itself, settles whether a specific attack is reachable in this deployment.
What Qodana found in the application The public Qodana report lists 65 findings across 21 files. That is a triage queue, not a count of exploitable vulnerabilities. Alerts repeat across modules, and some point to synthetic values in tests and documentation. The examples below show how a finding can lead to a concrete question about code, configuration, or dependencies.
A vulnerable dependency and an XML-processing call The Corporate Payments Portal’s web module parses XML drafts using XStream. Its build file, portal/build.gradle, declares version 1.4.7:
implementation 'com.thoughtworks.xstream:xstream:1.4.7' Qodana’s dependency check flags this version and lists known advisories. A separate taint finding points to the call that turns the XML string into Java objects:
new com.thoughtworks.xstream.XStream().fromXML(draft) These two signals answer different questions. The dependency alert says the application includes a version with known issues. The fromXML(draft) call takes its XML from the cpDeskDraft browser cookie. The controller checks only whether the cookie is empty. Because a client can change its cookie, this is considered untrusted input. XStream 1.4.7 does not use a type allowlist by default, so deserialization can instantiate unintended types. The exact impact depends on the payload and runtime environment.
The taint finding is labeled path traversal in this report, and the vulnerable API usage inspection did not produce a separate result. It would be misleading to tie a specific CVE to this call from these findings alone. Review whether XML deserialization is needed at all. If it is, update the dependency, allow only expected types, and test that unexpected XML is rejected.
A hardcoded fallback remains in configuration In the Corporate Payments Portal’s payment API, the legacy report bridge reads an intake key from a Spring configuration property. The colon inside the Spring placeholder defines a fallback value:
legacy-report-bridge:
intake-key: ${LEGACY_REPORT_BRIDGE_KEY:legacy-bridge-dev-key-9c1e} Spring reads the value after the colon when LEGACY_REPORT_BRIDGE_KEY is absent. The same fallback also appears in LegacyReportBridge‘s Java constructor. That component sends the resulting key to an internal reporting service as a bridge-key query parameter. In this benchmark, the value is synthetic, but a deployment that omits the environment variable could silently use a credential stored in source control.
Qodana’s Hardcoded passwords inspection flagged this example after we enabled detection based on suspicious variable names. Its default configuration would not flag this exact pattern. For production, remove the fallback in both the application.yml and LegacyReportBridge‘s @Value annotation. Require the key from an external secret source and fail startup if it is missing. Keep any development default confined to a development profile, and confirm whether the bridge is enabled in deployed environments.
For another example of Qodana detecting a hardcoded password, watch Helen’s video walkthrough:
A license finding raises a different question One finding concerns dependency policy rather than an exploitable bug. In the Corporate Payments Portal, Qodana’s license audit flags hibernate-core 6.5.3.Final, brought in transitively, because its LGPL-2.1-or-later license is on the report’s prohibited list for a project marked PROPRIETARY-LICENSE. Transitive means another dependency brings the component into the build; it may not appear in the developer’s direct dependency list.
The risk is making a distribution decision without reviewing the dependency’s obligations. This is a policy signal, not a legal conclusion or evidence that hibernate-core is insecure. A reviewer should confirm the project’s actual policy and distribution model, review the applicable terms, and then document an accepted exception or choose another dependency path. Repeated alerts across modules do not necessarily represent different libraries.
How to use the findings in a security review An alert becomes useful when it changes a review decision. The examples give us different kinds of evidence, and each leaves a different question open. The table summarizes selected signals:
Pattern What Qodana shows Review question Vulnerable dependency Advisories and an XML call What objects could XStream create from this cookie? Credential fallback Constant key in configuration Could the fallback run in production? License policy Transitive license policy alert Does the project policy allow it? A developer using JetBrains Air can open an agent’s diffs in context and leave comments on specific lines for the agent to act on. Qodana adds a different view, scanning the codebase and reporting issues found by its inspections. The developer can weigh both when deciding what to fix. The findings discussed in this article were derived solely from Qodana.
From there, the team checks whether input reaches each operation, whether an affected component is actually used, and which configuration applies in deployment. It fixes the relevant code or policy, tests the change, and records why any remaining alerts are accepted or dismissed. Supported checks can also run in CI, so later changes receive the same review signals.
Static analysis makes these questions visible and repeatable. It helps the team spend review time on specific paths and components, while developers supply the application context and decide whether a change is ready to ship.
You can explore the evidence in our public report. If you would like to run the experiment yourself, leave a comment, and we’ll get in touch to help with the setup.
Explore Qodana’s Report
FAQ Is AI-generated code more vulnerable than human-written code? There is no universal answer. Results depend on the tool, task, application context, and review process. This deliberately vulnerable benchmark cannot establish a comparative rate.
Can static analysis detect every security issue in AI-generated code? No. It can identify supported patterns and trace some data flows, but it can miss application-specific authorization rules and runtime behavior. Combine it with human review and targeted testing.
Can Qodana automatically secure AI-generated code? Qodana can automate supported inspections and surface findings for triage. It cannot determine whether every flagged path is exploitable or whether the application’s security requirements are complete.
Book a demo
Get more practical insights on code quality and security. Subscribe to the Qodana blog for new posts.